package com.kuqi.crs.settings.web.controller;

import com.kuqi.crs.settings.domain.User;
import com.kuqi.crs.settings.service.UserService;
import com.kuqi.crs.settings.service.impl.UserServiceImpl;
import com.kuqi.crs.util.MD5Util;
import com.kuqi.crs.util.PrintJson;
import com.kuqi.crs.util.ServiceFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author:kuqi
 * @createTime:2021/9/23 20:01
 * @description:Servlet->controller属于视图层view层
 */

@WebServlet(name = "UserController",value = {"/settings/user/login.do"})
public class UserController extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("正在进入用户控制模块");
        String servletPath = request.getServletPath();
        if ("/settings/user/login.do".equals(servletPath)){
            login(request,response);
        }else if ("/settings/user/xxx.do".equals(servletPath)){
//            xxxx(request,response);
        }
    }

    private void login(HttpServletRequest request, HttpServletResponse response){
        String loginAct = request.getParameter("loginAct");//获取用户名
        String loginPwd = request.getParameter("loginPwd");//获取密码
        //将明文密码转密文
        loginPwd = MD5Util.getMD5(loginPwd);
        String ip = request.getRemoteAddr();//获取ip地址

        //创建service
        UserService us = (UserService) ServiceFactory.getService(new UserServiceImpl());

        //调用service方法
        try {
            User user = us.checkLogin(loginAct,loginPwd, ip);//没有会报错
            HttpSession session = request.getSession();
            session.setAttribute("user",user);//当执行到这一步说明上面一步没有出错，将user存放到session域中

            /**
             * 当执行到这里时，说明没有任何异常，表示登录成功
             */
            PrintJson.printJsonFlag(response,true);//将数据封装成json，响应给前端

        } catch (Exception e) {
            e.printStackTrace();
            /**
             * 登录失败
             */
            String message = e.getMessage();//获取错误信息，是账号密码错误，还是ip被禁止，等
            Map<String,Object> map = new HashMap<String, Object>();
            map.put("success",false);
            map.put("msg",message);
            PrintJson.printJsonObj(response,map);//将map数据封装成json，响应给前端
        }


    }
}
